import json
from flask import request, render_template
import time
import os
import base64


def register(jsonrpc, web_path, upload_file,  db_addr, db_port, db_name):
    @jsonrpc.method('ICompanyTemplateSignService.upload_rc_code')
    def __upload_rc_code_service(handle_code, base64_str):
        time_id = str(int(time.time()))
        upload_path = upload_file + '\\'+time_id  # 以时间戳命名文件
        file_path = os.path.join(web_path, upload_path).replace('\\', '/')
        if not os.path.exists(file_path):  # 不存在改目录则会自动创建
            os.makedirs(file_path)
        # 保存文件
        save_path = os.path.join(file_path, time_id).replace(
            '\\', '/')  # windows下路径要转化
        img = base64.b64decode(base64_str.replace(
            'data:image/png;base64,', ''))
        file = open(save_path+'.png', 'wb')
        file.write(img)
        file.close()
        # 拼接文件url地址
        result = {'code': 200, 'desc': '上传成功', }
        result['url'] = os.path.join(
            upload_path, time_id+'.png').replace('\\', '/')
        return result
